import axios from "axios";
import qs from 'qs';
import router from '@/router'
import { getToken,removeToken } from "./token.js";
import { ElMessage } from "element-plus";
//创建axios
axios.defaults.baseURL = import.meta.env.VITE_BASEURL;
axios.interceptors.request.use((config) => {
  //config 拦截
  return config;
});

axios.defaults.headers["Content-Type"] = "application/json?chatset=utf-8";

//添加请求拦截器
axios.interceptors.request.use(
  (config) => {
    if (getToken("Token")) {
      config.headers["Token_Authorization"] = getToken("Token");
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//添加响应拦截器
axios.interceptors.response.use(
  (response) => {
    let { statusCode, message } = response.data;
    if (statusCode == 200) {
      return response;
    } else if (statusCode == 401) {
      ElMessage.error("权限不足!");
    } else if (statusCode == 403) {
      ElMessage.error('登录过期,请重新登录!')
      removeToken('Token')
      localStorage.removeItem('userInfo')
      localStorage.clear();
      router.push("/login");
    } else {
      return Promise.reject(message);
    }
  },
  (error) => {
    if (error.response != undefined && error.response.status === 401) {
      removeToken('Token')
      localStorage.removeItem('userInfo')
      localStorage.clear();
      ElMessage.error('登录过期,请重新登录!')
      router.replace('/login')
    }else{
      return Promise.reject(error)
    }
  }
);
export default axios;

export function get(url, params) {
  var token = localStorage.getItem("Token");
  return axios({
    method: "get",
    url: `${url}`,
    params: params,
    headers: {
      token: token,
    },
  });
}
export function post(url, params) {
  var token = localStorage.getItem("Token");
  return axios({
    method: "post",
    url: `${url}`,
    data: params,
    transformRequest: [
      function (data) {
        return qs.stringify(data, { allowDots: true });
      },
    ],
    headers: {
      token: token,
      "Content-Type": "application/x-www-form-urlencoded",
    },
  });
}

export function postJson(url, params) {
  var token = localStorage.getItem("Token");
  return axios({
    method: "post",
    url: `${url}`,
    data: params,
    headers: {
      token: token,
      "Content-Type": "application/json",
    },
  });
}

export function post2(url, params) {
  var token = localStorage.getItem("Token");
  return axios({
    method: "post",
    url: `${url}`,
    data: params,
    headers: {
      token: token,
      "Content-Type": "multipart/form-data",
    },
  });
}

export function postFile(url, params) {
  var token = localStorage.getItem("Token");
  let formdata = new FormData();
  formdata.append("file", params);
  return axios({
    method: "post",
    url: url,
    data: formdata, // 注意这里应该是formdata而不是params
    // 移除了Content-Type的手动设置，让FormData自动管理
    headers: {
      token: token,
      "Content-Type": "multipart/form-data",
    },
  });
}